<template>
  <div class="w-full h-full p-4">
    <h1 class="text-2xl font-bold mb-4">Log Page</h1>
    <WebSocketStatusIndicator />
    <el-button class="bg-red-500 text-white ml-4" @click="clearMessages">清除日志</el-button>

    <el-table :data="messages" style="width: 100%" @row-click="handleRowClick">
      <el-table-column type="index" label="序号" width="100" prop="index" />
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="createTime" label="Timestamp" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="message" label="Content" />
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import { ElTable, ElTableColumn, ElButton, ElMessage } from 'element-plus';
import { useLogStore } from './logStore.ts';
import { storeToRefs } from 'pinia';
import WebSocketStatusIndicator from '@/components/WebSocketStatusIndicator.vue';
import useClipboard from 'vue-clipboard3';

const { toClipboard } = useClipboard();
const logStore = useLogStore();
const { messages } = storeToRefs(logStore);

const handleRowClick = (row: any) => {
  toClipboard(JSON.stringify(row));
  ElMessage.success('复制成功');
};

onMounted(() => {
  logStore.unBindWebSocketListener();
  logStore.setupWebSocketListener();
});

onUnmounted(() => {});

const clearMessages = () => {
  logStore.clearMessages();
};

const formatDate = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString();
};
</script>
